package perform.startup;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;

import perform.database.DatabaseProcessor;
import perform.database.ManyToManyProcessor;
import perform.database.TableProcessor;

public abstract class StartupBroker {
	
	protected Connection connection;
	protected DatabaseProcessor databaseProcessor;
	
	protected StartupBroker(Connection connection, DatabaseProcessor databaseProcessor){
		this.connection = connection;
		this.databaseProcessor = databaseProcessor;
	}
	
	public void prepareDatabase() throws SQLException{
		if(!databaseExists()){
			executeUpdate(databaseProcessor.getCreateQuery());
		}
		useDatabase();
		List<TableProcessor> tables = databaseProcessor.getTables();
		for(int i = 0; i < tables.size(); i++){
			if(!tableExists(tables.get(i).getName())){
				executeUpdate(tables.get(i).getCreateQuery());
			} else {
				tables.get(i).setExisted(true);
			}
		}
		for(int i = 0; i < tables.size(); i++){
			if(tables.get(i).hasConstraints() && !tables.get(i).isExisted()){
				executeUpdate(tables.get(i).getAlterQuery());
			}
		}
		List<ManyToManyProcessor> manyToManies = databaseProcessor.getManyToManies();
		if(manyToManies != null && !manyToManies.isEmpty()){
			for(int i = 0; i < manyToManies.size(); i++){
				if(!tableExists(manyToManies.get(i).getName())){
					executeUpdate(manyToManies.get(i).getCreateQuery());
				}
			}
		}
	}
	
	private boolean databaseExists() throws SQLException{
		Statement statement = connection.createStatement();
		ResultSet rs = statement.executeQuery("show databases like '" + databaseProcessor.getName() + "' ;");
		if(rs.next()){
			statement.close();
			return true;
		}
		statement.close();
		return false;
	}
	private void useDatabase() throws SQLException{
		Statement statement = connection.createStatement();
		statement.execute("use `" + databaseProcessor.getName() + "` ;");
		statement.close();
	}
	private boolean tableExists(String tableName) throws SQLException{
		Statement statement = connection.createStatement();
		ResultSet rs = statement.executeQuery("show tables like '" + tableName + "' ;");
		if(rs.next()){
			statement.close();
			return true;
		}
		statement.close();
		return false;
	}
	
	public void drop() throws SQLException{
		executeUpdate(databaseProcessor.getDropQuery());
	}
	
	protected abstract void executeUpdate(String query) throws SQLException;

}
